package qfcfg

import (
	"encoding/xml"
	"io/ioutil"
	"os"

	"github.com/fsnotify/fsnotify"
	qflog "github.com/qf-tech/qftech-base/pkg/log"
)

// SConfig def
type SConfig struct {
	XMLName xml.Name `xml:"config"` // 指定最外层的标签为config
	Server  SServer  `xml:"server"` // 读取sServer配置项，并将结果保存到Server变量中
	Client  SClient  `xml:"client"` // 读取sServer配置项，并将结果保存到Server变量中
}

// SServer def
type SServer struct {
	IP       string `xml:"ip"`       // 读取ip
	Port     int    `xml:"port"`     // 读取port
	Username string `xml:"username"` // 读取用户名
	Password string `xml:"password"`
	HttpIP   string `xml:"httpip"`
	Httpport int    `xml:"httpport"`
	WebDir   string `xml:"webdir"`
}

// SClient def
type SClient struct {
	TeuID   string `xml:"teuid"`
	SysType string `xml:"systype"`
	Timeout int    `xml:"timeout"`
}

// ServerConfig export var
var ServerConfig SConfig

// readConfig def
func readConfig(path string) {
	file, err := os.Open(path) // For read access.
	if err != nil {
		qflog.Sugare.Errorf("error: %v", err)
		return
	}
	defer file.Close()
	data, err := ioutil.ReadAll(file)
	if err != nil {
		qflog.Sugare.Errorf("error: %v", err)
		return
	}

	ServerConfig = SConfig{}
	err = xml.Unmarshal(data, &ServerConfig)
	if err != nil {
		qflog.Sugare.Errorf("error: %v", err)
		return
	}

	qflog.Sugare.Infof("ip:%s port:%d", ServerConfig.Server.IP, ServerConfig.Server.Port)
}

// InitConfig def
func InitConfig() {
	readConfig("config.xml")

	// 监控文件
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		qflog.Sugare.Errorf("error:", err)
	}
	defer watcher.Close()

	// done := make(chan bool)
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				qflog.Sugare.Infof("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					qflog.Sugare.Infof("modified file:", event.Name)
					readConfig("config.xml")
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				qflog.Sugare.Errorf("error:", err)
			}
		}
	}()

	err = watcher.Add("config.xml")
	if err != nil {
		qflog.Sugare.Errorf("error:", err)
	}
	// <-done
}
